# 将本地 mongo 数据更新到 阿里云

import time
import datetime
import pymongo

AlI_CLOUD_URL = "mongodb://47.98.146.210:27017" # 阿里云地址
LOCATIONS_URL = "mongodb://127.0.0.1:27017" # 本地地址
PAGE_SIZE = 10000

location_client = pymongo.MongoClient(LOCATIONS_URL)
location_db = location_client["darenji_anchors"]
location_anchors = location_db["anchors"]
location_detail = location_db["zbsj_detail"]

cloud_client = pymongo.MongoClient(AlI_CLOUD_URL)
cloud_db = cloud_client["WeChat"]
cloud_zbsj_list = cloud_db["zbsj_list"]
cloud_zbsj_detail = cloud_db["zbsj_detail"]


# 数据库去重
def foemat_location_database(begin_id, end_id):

    origin_count = location_detail.count_documents({"drjId": { "$gte": begin_id, "$lt": end_id }})
    distinct_count = location_detail.distinct("drjId", {"drjId": {"$gte": begin_id, "$lt": end_id}})

    print("原始数量：{}".format(origin_count))
    print("去重数量：{}".format( len(distinct_count) ))

    if origin_count != len(distinct_count):
        print("----- anchors 去重开始 -----")

        for item in distinct_count:
            # 复制第一条id相同的数据
            repeating = location_detail.find_one({'drjId': item})
            # 删除所有id相同的数据
            result = location_detail.delete_many({'drjId': item})
            # 把刚刚复制的数据加入一条到数据库
            location_detail.insert_one(repeating)

        print("----- anchors 去重结束-----")

        distinct_count = location_detail.distinct("drjId", {"drjId": {"$gte": begin_id, "$lt": end_id}})
        print("去重数量：{}".format(len(distinct_count)))
    else:
        print("不需要去重")


# 将本地数据库更新到线上
def upload_data(page):
    # res = location_anchors.find({}).sort([("drjId", 1)]).skip(page * PAGE_SIZE).limit(PAGE_SIZE)
    res = location_anchors.find({}).sort([("drjId", -1)]).skip(0).limit(9393)
    data = []
    for item in res:
        del(item["_id"])
        data.append(item)
    print("------ 开始更新数据 ------")
    cloud_zbsj_list.insert_many(data, ordered=False)
    print("------ 数据更新完成 ------")


# 将本地数据库更新到线上
def upload_data_detail(page):
    # res = location_detail.find({}).sort([("drjId", 1)]).skip(page * PAGE_SIZE).limit(PAGE_SIZE)
    res = location_detail.find({}).sort([("drjId", -1)]).skip(0).limit(9393)
    # res = location_anchors.find({}).sort([("drjId", -1)]).skip(0).limit(9393)
    data = []
    for item in res:
        del(item["_id"])
        data.append(item)
    print("------ 开始更新数据 ------")
    cloud_zbsj_detail.insert_many(data, ordered=False)
    print("------ 数据更新完成 ------")


# 更新 anchorId
def upload_anchorId(begin, end):
    list = cloud_zbsj_list.find({"drjId": {"$gt": begin, "$lte": end}}).sort([("drjId", 1)])
    drjId_list = []
    for item in list:
        drjId_list.append({
            "drjId": item["drjId"],
            "anchorId": item["anchorId"]
        })
    
    for item in drjId_list:
        id = item["drjId"]
        detail_one = cloud_zbsj_detail.find_one({"drjId": id})
        detail_one["anchorId"] = item["anchorId"]
        cloud_zbsj_detail.update_one({"drjId": id}, {"$set": detail_one})
        print("drjId = {} done".format(id))

def upload_anchorId2():
    list = cloud_zbsj_detail.find({"anchorId": None}).sort([("drjId", 1)])
    drjId_list = []
    for item in list:
        drjId_list.append({
            "drjId": item["drjId"]
        })
    
    for item in drjId_list:
        id = item["drjId"]
        try:
            list_one = cloud_zbsj_list.find_one({"drjId": id})
            detail_one = cloud_zbsj_detail.find_one({"drjId": id})
            detail_one["anchorId"] = list_one["anchorId"]
            cloud_zbsj_detail.update_one({"drjId": id}, {"$set": detail_one})
            print("drjId = {} done".format(id))
        except:
            print("drjId = {} no data".format(id))


# 更新 fansNumber
def upload_fansNumber(begin, end):
    list = cloud_zbsj_list.find({"drjId": {"$gt": begin, "$lte": end}}).sort([("drjId", 1)])
    drjId_list = []
    for item in list:
        drjId_list.append({
            "drjId": item["drjId"],
            "fansNumber": item["fansNumber"]
        })
    
    for item in drjId_list:
        id = item["drjId"]
        detail_one = cloud_zbsj_detail.find_one({"drjId": id})
        detail_one["fansNumber"] = item["fansNumber"]
        cloud_zbsj_detail.update_one({"drjId": id}, {"$set": detail_one})
        print("drjId = {} done".format(id))


# def anchor_settle():
#     new_anchor_list_count = cloud_zbsj_list.count_documents({"drjId": None})
#     print("新主播数: {}".format(new_anchor_list_count))
#     if new_anchor_list_count > 0:
#         print("------ 需要整理 ------")
#         new_anchor_list = cloud_zbsj_list.find({"drjId": None})
#         for item in new_anchor_list:
#             # 查询是否重复
#             repetition_num = cloud_zbsj_list.count_documents("anchorName": item["anchorName"])
#             if repetition_num > 0:
#                 continue
            
#     else:
#         print("不需要整理")


def estimate_uv(ws_uv, ws_pv, lived_pv):
    # ws_uv: webscoket最后一次取到的UV
    # ws_pv: webscoket最后一次取到的PV
    # lived_pv：回放中获取到的PV
    ws_uv = int(ws_uv)
    ws_pv = int(ws_pv)
    lived_pv = int(lived_pv)

    pv_changed = lived_pv - ws_pv
    uv_changed = int( pv_changed * (ws_uv / ws_pv) )

    uv_result = ws_uv + uv_changed

    return uv_result


if __name__ == '__main__':
    print(estimate_uv(10000, 12000, 14000))
